package com.hbnu.gui.controller;

import com.hbnu.common.entity.User;
import com.hbnu.common.factory.ServiceFactory;
import com.hbnu.common.response.ServiceResponse;
import com.hbnu.common.service.LoginService;

import com.hbnu.common.util.CheckUtil;
import com.hbnu.gui.constant.Views;
import com.hbnu.gui.util.AlertUtil;
import com.hbnu.gui.util.WindowManager;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.scene.image.ImageView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginController {
    @FXML
    private StackPane windowMinimizeBtn;
    @FXML
    private StackPane windowCloseBtn;

    @FXML
    private TextField usernameInput;
    @FXML
    private PasswordField passwordInput;
    @FXML
    private Button loginBtn;
    @FXML
    private Hyperlink registerBtn;
    @FXML
    private Hyperlink forgetPasswordBtn;

    @FXML
    private ImageView usernameImgView;
    @FXML
    private ImageView passwordImgView;
    @FXML
    private ImageView eyeImgView;

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    private final WindowManager windowManager = WindowManager.getInstance();
    private final LoginService loginService = ServiceFactory.getLoginService();

    @FXML
    public void windowMinimizeBtnClicked() {
        windowManager.getPrimaryStage().setIconified(true);
    }

    @FXML
    public void windowCloseBtnClicked() {
        windowManager.closeView(Views.LOGIN);
    }

    @FXML
    public void loginButtonClicked() {
        String username = usernameInput.getText().trim();
        String errorMessage = CheckUtil.checkUsername(username);

        if (errorMessage != null) {
            AlertUtil.showAlert(Alert.AlertType.WARNING, "登录失败", errorMessage);
            return;
        }

        String password = passwordInput.getText().trim();
        errorMessage = CheckUtil.checkPassword(password);

        if (errorMessage != null) {
            AlertUtil.showAlert(Alert.AlertType.WARNING, "登录失败", errorMessage);
            return;
        }

        logger.info("收到登录请求：用户名={}", username);
        ServiceResponse<User> response = loginService.handleLogin(username, password);

        if (response.isSuccess()) {
            logger.info("登录成功：用户名={}", username);
            windowManager.closeView(Views.LOGIN);
            windowManager.showView(Views.MAIN);
        } else {
            logger.error("登录失败：用户名={}，原因={}", username, response.getErrorMessage());
            AlertUtil.showAlert(Alert.AlertType.ERROR, "登录失败", response.getErrorMessage());
        }
    }

    @FXML
    public void registerButtonClicked() {
        windowManager.closeView(Views.LOGIN);
        windowManager.showView(Views.REGISTER);
    }
}
